package com.jtw.common.globalErrorController;

import com.jtw.common.bean.Result.Message;
import com.jtw.common.bean.enums.ReqCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * DESCRIPT:处理springboot默认的/error错误处理方式
 *
 * @author cjsky666
 * @date 2018/9/26 15:02
 */
@Controller
@Slf4j
public class GlobalControllertroller implements ErrorController {

    @RequestMapping(value = "/error",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Message error(HttpServletRequest request){
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        switch (statusCode){
            case 401: return ReqCode.Error401.getMessage();
            case 402: return ReqCode.Error402.getMessage();
            case 403: return ReqCode.Error403.getMessage();
            case 404: return ReqCode.Error404.getMessage();
            case 500: return ReqCode.Error500.getMessage();
            default:return ReqCode.ServiceError.getMessage();
        }
    }

    @RequestMapping(value = "/error",produces = MediaType.TEXT_HTML_VALUE)
    public String errorHtml(HttpServletRequest request){
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        switch (statusCode){
            case 401:
                return "error/401";
            case 402:
                return "error/402";
            case 403:
                return "error/403";
            case 404:
                return "error/404";
            case 500:
                return "error/500";
            default:
                return "error/404";
        }
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
}
